<?php

/**
 * 商品管理
 * @author Administrator
 */
namespace Operation\Controller;

use Operation\Model\Upload;
use Operation\Model\Goods;
use Operation\Model\Model;
use Operation\Model\Export;
use Think\Controller;
use Think\IReq;
use Think\IFilter;
use Think\JSON;
use Think\Page;
use Think\ISafe;
use Think\Log;
use Think\Util;

class GoodsController extends ComController{

    public $checkRight = 'all';
    public $layout = 'admin';
    private $data = array();

    public function init() {
        
    }

    /**
     * 选择规格数据
     */
    function select_spec() {

        $seller_id  = IFilter::act(IReq::get('seller_id'),'int');
        $where = array(
            'is_del' => 0,
            'seller_id' => $seller_id
        );
        $spec_obj = M('spec');
        $spec = $spec_obj->where($where)->select();
        //dump(JSON::encode($spec));die;
        $this->assign('seller_id', $seller_id);
        $this->assign('spec', JSON::encode($spec));
        $this->display();
    }

    /**
     * @brief 商品添加中图片上传的方法
     */
    public function goods_img_upload() {
        //调用文件上传类
        $photoObj = new Upload();
        
        $photo = current($photoObj->run());

        //判断上传是否成功，如果float=1则成功
        if ($photo['flag'] == 1) {
            $result = array(
                'flag' => 1,
                'img' => $photo['img']
            );
        } else {
            $result = array('flag' => $photo['flag']);
        }
        
        echo JSON::encode($result);
    }

    /**
     * @brief 商品模型添加/修改
     */
    public function model_update() {
        // 获取POST数据
        $model_id = IFilter::act(IReq::get("model_id"), 'int');
        $model_name = IFilter::act(IReq::get("model_name"));
        $attribute = IFilter::act(IReq::get("attr"));
        $spec = IFilter::act(IReq::get("spec"));

        //初始化Model类对象
        $modelObj = new Model();

        //更新模型数据
        $result = $modelObj->model_update($model_id, $model_name, $attribute, $spec);

        if ($result) {
            $this->redirect('model_list');
        } else {
            //处理post数据，渲染到前台
            $result = $modelObj->postArrayChange($attribute, $spec);
            $this->data = array(
                'id' => $model_id,
                'name' => $model_name,
                'model_attr' => $result['model_attr'],
                'model_spec' => $result['model_spec']
            );
            $this->assign('model', $this->data);
            $this->redirect('model_edit', false);
        }
    }

    /**
     * @brief 商品模型列表
     */
    public function model_list() {
        $p = $_GET['p'] ? $_GET['p'] : 1;
        $page = 20;
        $model_obj = M('model');
        $where = array(
            'is_del' => '0',
        );
        $order = 'id desc';
        $model = $model_obj->where($where)->order($order)->page($p . ',' .$page)->select();
        
        $this->assign('model' , $model);
        $this->display();
    }
    
    /**
     * @brief 商品模型修改
     */
    public function model_edit() {
        // 获取POST数据
        $id = IFilter::act(IReq::get("id"), 'int');
        if ($id) {
            //初始化Model类对象
            $modelObj = new Model();
            //获取模型详细信息
            $model_info = $modelObj->get_model_info($id);
            //dump($model_info);die;
            
        }
        $this->assign('model_attr',  JSON::encode($model_info['model_attr']) ? JSON::encode($model_info['model_attr']) : 'null');
        $this->assign('model_spec',  JSON::encode($model_info['model_spec']) ? JSON::encode($model_info['model_spec']) : 'null');

        $this->assign('model',$model_info);
        $this->display();
    }

    /**
     * @brief 商品模型删除
     */
    public function model_del() {
        //获取POST数据
        $id = IFilter::act(IReq::get("id"), 'int');
        $id = !is_array($id) ? array($id) : $id;

        if ($id) {
            foreach ($id as $key => $val) {
                //初始化goods_attribute表类对象
                $goods_attrObj = new IModel("goods_attribute");

                //获取商品属性表中的该模型下的数量
                $attrData = $goods_attrObj->query("model_id = " . $val);
                if ($attrData) {
                    $this->redirect('model_list', false);
                    Util::showMessage("无法删除此模型，请确认该模型下以及回收站内都无商品");
                }

                //初始化Model表类对象
                $modelObj = new IModel("model");

                //删除商品模型
                $result = $modelObj->del("id = " . $val);
            }
        }
        $this->redirect('model_list');
    }

    /*
     * @breif 后台添加给商品规格
     * 
     */
    function search_spec() {
        $this->layout = '';
        $data = array();

        //获得model_id的值
        $model_id = IFilter::act(IReq::get('model_id'), 'int');
        $goods_id = IFilter::act(IReq::get('goods_id'), 'int');
        $specId = '';

        if ($goods_id) {
            $tb_goods = M('goods');
            $goods_info = $tb_goods->where(array('id' => $goods_id))->field('spec_array')->find();
            $data['goodsSpec'] = JSON::decode($goods_info['spec_array']);
            if ($data['goodsSpec']) {
                foreach ($data['goodsSpec'] as $item) {
                    $specId .= $item['id'] . ',';
                }
            }
        } else if ($model_id) {
            $modelObj = M('model');
            $modelInfo = $modelObj->where(array('id' => $model_id))->field('spec_ids')->find();
            $specId = $modelInfo['spec_ids'] ? $modelInfo['spec_ids'] : '';
        }

        if ($specId) {
            $specObj = M('spec');
            $data['specData'] = $specObj->where(array('id in (' . trim($specId, ',') . ')'))->select;
        }

        $this->assign('specData',  JSON::encode($data['specData']) ? JSON::encode($data['specData']) : 'null');
        $this->assign('goodsSpec',  $data['goodsSpec'] ? $data['goodsSpec'] : 'null');
        $this->display();
    }

    /**
     * @brief 商品添加和修改视图
     */
    public function goods_edit() {
        
        $sessionName = ISafe::name();
        $sessionId = ISafe::id();
        $goods_id = IFilter::act(IReq::get('id'), 'int');

        //初始化数据
        $goods_class = new Goods();

        //获取所有商品扩展相关数据
        $data = $goods_class->edit($goods_id);

        if ($goods_id && !$data) {
            die("没有找到相关商品！");
        }
        $this->assign('good_id', $goods_id);
        $this->assign('form', JSON::encode($data['form']) ? JSON::encode($data['form']) : 'null');
        $this->assign('spec_array', $data['product'][0]['spec_array'] ? $data['product'][0]['spec_array'] : 'null');
        $this->assign('product', JSON::encode($data['product']) ? JSON::encode($data['product']) : 'null');
        $this->assign('goods_photo', JSON::encode($data['goods_photo']) ? JSON::encode($data['goods_photo']) : 'null');
        $this->assign('data', $data);
        
        if($data['goods_attr']){
            $goods_attr = array();
            foreach ($data['goods_attr'] as  $key => $value) {
                $valArray = explode(',',$value);	
                $goods_attr[] = '"attr_id_'.$key.'[]":"'.join(";",IFilter::act($valArray)).'"';
                $goods_attr[] = '"attr_id_'.$key.'":"'.join(";",IFilter::act($valArray)).'"';
            }
        }
        $this->assign('goods_attr', join(',',$goods_attr) ? '{'.join(',',$goods_attr).'}' : 'null');
        
        $categoryObj = M('category');
        $categories = $categoryObj->select();
        $partnet = Goods::categoryParentStruct($categories);

        $this->assign('sessionName', $sessionName);
        $this->assign('sessionId', $sessionId);
        $this->assign('json_categories', JSON::encode($categories) ? JSON::encode($categories) : 'null');
        $this->assign('json_partnet', JSON::encode($partnet) ? JSON::encode($partnet) : 'null');
        $category_id = implode(',', $data['goods_category']);
        if(preg_match(',', $category_id)){
            $where = array(
                'id in (' .$category_id . ')'
            );
        }else{
             $where = array(
                'id' => $category_id
            );
        }
        
        $good_category = $categoryObj->where($where)->select();
        $this->assign('default_cat', JSON::encode($good_category) ? JSON::encode($good_category) : 'null');
        
        //默认货号
        $defaultProductNo = $goods_class->createGoodsNo();
        $this->assign('defaultProductNo', $defaultProductNo);
        
        //商户
        $seller = M('seller')->where(array('is_del' => '0'))->select();
        $this->assign('seller', $seller);
        
        //模型
        $model = M('model')->where(array('is_del' => '0'))->select();
        $this->assign('model', $model);
        
        //品牌
        $band = M('brand')->where(array('is_del' => '0'))->select();
        $this->assign('brand', $band);
        
        $this->display();
    }

    /**
     * @brief 保存修改商品信息
     */
    function goods_update() {
        $id = IFilter::act(IReq::get('id'), 'int');
        //$callback = IFilter::act(IReq::get('callback'));
        //$callback = strpos($callback, 'goods/goods_list') === false ? '' : $callback;

        //检查表单提交状态
        if (!$_POST) {
            die('请确认表单提交正确');
        }

        //初始化商品数据
        unset($_POST['id']);
        unset($_POST['callback']);

         Goods::update($id, $_POST);

        //记录日志
        //Log::writes('operation', array("管理员:" . ISafe::get('admin_name'), "修改商品信息", "商品ID：" . $id . "，名称：" . IFilter::act(IReq::get('name'))));

        $this->redirect("Goods/goods_list");
    }

    /**
     * @brief 删除商品
     */
    function goods_del() {
        //post数据
        $id = IFilter::act(IReq::get('id'), 'int');

        if ($id) {
            $id = is_array($id) ? array('IN' , join(',' , $id)) : $id;
            $code = M('code')->where(array('good_id' => $id))->select();
            if ($code) {
                $this->error('该商品存在二维码，请谨慎删除', U('Goods/goods_list'));
            } else {
                $goodsObj = M('goods');
                $data = array(
                    'is_del' => 1,
                    'id' => $id
                );
                $goodsObj->save($data);
                $this->success('删除成功', U('Goods/goods_list'));
            }
        } else {
            $this->error('请选择要删除的数据', U('Goods/goods_list'));
        }
    }
    
    /*
     * @brief 商品回收站
     */
    public function goods_recycle_list() {
        $p = IFilter::act(IReq::get('p'), 'int') ? IFilter::act(IReq::get('p'), 'int') : 1;
        $goodObj = M('goods as go');
        $join1 = 'sm_brand as b on go.brand_id = b.id';
        $join2 = '';
        $where = array(
            'go.is_del' => 1
        );
        $field = 'go.* , b.name as brand_name';
        $order = 'go.sort asc, go.id desc';
        $page = '15';
        $goods = $goodObj->join($join1)->where($where)->order($order)->field($field)->page($p . ",$page")->select();
        //dump($goods);die;
        $count = $goodObj->where($where)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //print_r($show);die;

        $this->assign('page', $show);
        $this->assign('goods', $goods);
        $this->display();
    }

    /**
     * @brief 商品彻底删除
     * */
    public function goods_recycle_del() {
        //post数据
        $id = IFilter::act(IReq::get('id'), 'int');

        if ($id) {
            $id = is_array($id) ? array('IN', join(',', $id)) : $id;
            $data = array(
                'id' => $id
            );
            $goodsObj = M('goods');
            $goodsObj->where($data)->delete();
            //dump($goodsObj->getLastSql());die;
            $this->success('删除成功', U('Goods/goods_recycle_list'));
        } else {
            $this->error('请选择要删除的数据', U('Goods/goods_recycle_list'));
        }
    }

    /**
     * @brief 商品还原
     * */
    public function goods_recycle_restore() {
        //post数据
        $id = IFilter::act(IReq::get('id'), 'int');
        if ($id) {
            $id = is_array($id) ? array('IN', join(',', $id)) : $id;
            $data = array(
                'is_del' => 0,
                'id' => $id
            );
            $goodsObj = M('goods');
            $goodsObj->save($data);
            $this->success('还原成功', U('Goods/goods_recycle_list'));
        } else {
            $this->error('请选择要还原的数据', U('Goods/goods_recycle_list'));
        }
    }

    /**
     * @brief 商品列表
     */
    public function goods_list() {
        //搜索条件
        $search = IFilter::act(IReq::get('search'));
        $p = IFilter::act(IReq::get('p'), 'int') ? IFilter::act(IReq::get('p'), 'int') : 1;

        //条件筛选处理
        list($join, $where) = Goods::getSearchCondition($search);

        //dump($where);die;
        //拼接sql
        $goodsHandle = M('goods as go');
        $field = 'go.* , b.name as brand_name, s.name as seller';
        $order = 'go.create_time desc, go.sort asc, go.id desc';
        $page = '15';

        $goods = $goodsHandle->where($where)->join($join)->order($order)->field($field)->page($p . ",$page")->select();
        //dump($goodsHandle->getLastSql());
        //dump($goods);die;
        $codeObj = M('code');
        foreach ($goods as $key => $value) {
            $goods[$key]['category'] = Goods::getGoodsCategory($value['id']);
            $sql = 'select status,count(*) counts from sm_code where is_del = 0 and good_id = '. $value['id'] .' group by status';
            $code = $codeObj->query($sql);
            foreach ($code as $val){
                $goods[$key]['code'][$val['status']] = $val['counts'];
                $goods[$key]['code']['counts'] +=  $val['counts'];
            }
            $goods[$key]['code'][1] = $goods[$key]['code'][1] ? $goods[$key]['code'][1] : 0;
            $goods[$key]['code'][2] = $goods[$key]['code'][2] ? $goods[$key]['code'][2] : 0;
            $goods[$key]['code']['counts'] = $goods[$key]['code']['counts'] ? $goods[$key]['code']['counts'] : 0;
        }
        
        $count = $goodsHandle->where($where)->join($join)->count();
        //分页跳转的时候保证查询条件
        $param = '';
        foreach ($search as $key => $val) {
            $k = 'search[' . $key . ']';
            if($val){
                $param .= $k . '=' . $val . '&';
            }
        }
        unset($_GET['search']);
        $Page = new Page($count, $page);
        //dump($Page->parameter);die;
        $show = $Page->show($param);

        $this->assign('search', JSON::encode($search));
        $this->assign('page', $show);
        $this->assign('goods',$goods);
        
        //商品品牌
        $brand = M('brand')->select();
        $this->assign('brand',$brand);
        //商品分类
        $categoryObj = M('category');
        $categories = $categoryObj->select();
        $partnet = Goods::categoryParentStruct($categories);
        if (isset($search['category_id'])) {
            $category = $categoryObj->where(array( 'id' => $search['category_id']))->select();
            $this->assign('default_cat', JSON::encode($category) ? JSON::encode($category) : 'null');
        }
        $this->assign('json_categories', JSON::encode($categories) ? JSON::encode($categories) : 'null');
        $this->assign('json_partnet', JSON::encode($partnet) ? JSON::encode($partnet) : 'null');
        
        $this->display();
    }

    //商品导出 Excel
    public function goods_export() {
        
        $search = IFilter::act(IReq::get('search'));

        //条件筛选处理
        list($join, $where) = Goods::getSearchCondition($search);

        //dump($where);die;
        //拼接sql
        $goodsHandle = M('goods as go');
        $field = 'go.* , b.name as brand_name';
        $order = 'go.sort asc, go.id desc';

        $goods = $goodsHandle->where($where)->join($join)->order($order)->field($field)->select();
        
        $export = new Export();
        $header = array('ID','商品名称','分类','品牌','销售价','市场价','添加时间');
        $data = array();
        foreach ($goods as $key => $value){
            $data[$key] = array(
                'id' => $value['id'],
                'name' => $value['name'],
                'category' => Goods::getGoodsCategory($value['id']),
                'brand_name' => $value['brand_name'],
                'sell_price' => $value['sell_price'],
                'market_price' => $value['market_price'],
                'create_time' => $value['create_time']
            );
        }
        $export->export($data,$header);
    }

    /**
     * @brief 商品分类添加、修改
     */
    function category_edit() {
        $category_id = IFilter::act(IReq::get('cid'), 'int');
        $categoryObj = M('category');
        if ($category_id) {
            $category = $categoryObj->find($category_id);
            $this->assign('category_id', $category_id);
            $this->assign('json_category', JSON::encode($category));
        }
        $categories = $categoryObj->select();
        $partnet = Goods::categoryParentStruct($categories);
        
        if($category['parent_id']){
            $default_cat = $categoryObj->where(array('id' => $category['parent_id']))->select();
            $this->assign('default_cat', JSON::encode($default_cat));
        }
        
        $this->assign('json_categories', JSON::encode($categories));
        $this->assign('json_partnet', JSON::encode($partnet));
        $this->display();
    }

    /**
     * @brief 保存商品分类
     */
    function category_save() {
        //获得post值
        $category_id = IFilter::act(IReq::get('id'), 'int');
        $name = IFilter::act(IReq::get('name'));
        $parent_id = IFilter::act(IReq::get('parent_id'), 'int');
        $sort = IFilter::act(IReq::get('sort'), 'int');
        $title = IFilter::act(IReq::get('title'));
        $keywords = IFilter::act(IReq::get('keywords'));
        $descript = IFilter::act(IReq::get('descript'));

        if (!$name) {
            $this->redirect('Goods/category_list');
        }

        $tb_category = M('category');
        $category_info = array(
            'name' => $name,
            'parent_id' => $parent_id,
            'sort' => $sort,
            'keywords' => $keywords,
            'descript' => $descript,
            'title' => $title
        );
        if ($category_id) {         //保存修改分类信息
            $where = "id=" . $category_id;
            $tb_category->where($where)->save($category_info);
        } else {            //添加新商品分类
            $res = $tb_category->add($category_info);
        }
        $this->redirect('Goods/category_list');
    }

    /**
     * @brief 删除商品分类
     */
    function category_del() {
        $category_id = IFilter::act(IReq::get('cid'), 'int');
        if ($category_id) {
            $tb_category = new IModel('category');
            $catRow = $tb_category->getObj('parent_id = ' . $category_id);

            //要删除的分类下还有子节点
            if (!empty($catRow)) {
                $this->category_list();
                Util::showMessage('无法删除此分类，此分类下还有子分类，或者回收站内还留有子分类');
                exit;
            }

            if ($tb_category->del('id = ' . $category_id)) {
                $tb_category_extend = M('category_extend');
                $tb_category_extend->del('category_id = ' . $category_id);
                $this->redirect('category_list');
            } else {
                $this->category_list();
                $msg = "没有找到相关分类记录！";
                Util::showMessage($msg);
            }
        } else {
            $this->category_list();
            $msg = "没有找到相关分类记录！";
            Util::showMessage($msg);
        }
    }

    /**
     * @brief 商品分类列表
     */
    function category_list() {
        $tb_category = M('category');
        $category = $tb_category->order('parent_id desc, sort asc')->select();
        if($category){
            $data = Goods::sortdata($category);
        }
        //dump($data);die;
        $this->assign('category',$data);
        $this->display();
    }

    //修改规格页面
    function spec_edit() {
        $this->layout = '';

        $id = IFilter::act(IReq::get('id'));
        $seller_id = IFilter::act(IReq::get('seller_id'));

        $dataRow = array(
            'id' => '',
            'name' => '',
            'type' => '',
            'value' => '',
            'note' => '',
            'seller_id' => $seller_id,
        );

        if ($id) {
            $obj =M('spec');
            $dataRow = $obj->find($id);
            $dataRow['spec'] = JSON::decode($dataRow['value']);
        }

        
        $this->assign('id',$id);
        $this->assign('dataRow',$dataRow);
        $this->display();
    }

    //增加或者修改规格
    function spec_update() {
        $id = IFilter::act(IReq::get('id'), 'int');
        $name = IFilter::act(IReq::get('name'));
        $specType = IFilter::act(IReq::get('type'));
        $value = IFilter::act(IReq::get('value'));
        $note = IFilter::act(IReq::get('note'));
        $seller_id = IFilter::act(IReq::get('seller_id'), 'int');

        //要插入的数据
        if (is_array($value) && isset($value[0]) && $value[0]) {
            $value = array_filter($value);
            $value = array_unique($value);
            $value = $value ? JSON::encode($value) : '';
        }

        if (!$value) {
            die(JSON::encode(array('flag' => 'fail', 'message' => '规格值不能为空,请填写规格值或上传规格图片')));
        }

        if (!$name) {
            die(JSON::encode(array('flag' => 'fail', 'message' => '规格名称不能为空')));
        }

        $editData = array(
            'id' => $id,
            'name' => $name,
            'value' => $value,
            'type' => $specType,
            'note' => $note,
            'seller_id' => $seller_id,
        );

        //执行操作
        $obj = M('spec');
        //$obj->setData($editData);

        //更新修改
        if ($id) {
            $where = array('id' => $id);
            if ($seller_id) {
                $where['seller_id'] = $seller_id;
            }
            //$result = $obj->update($where);
            $result= $obj->save($editData, $where);
        }
        //添加插入
        else {
            $result = $obj->add();
            $result = $obj->add($editData);
        }

        //执行状态
        if ($result === false) {
            die(JSON::encode(array('flag' => 'fail', 'message' => '数据库更新失败')));
        } else {
            //获取自动增加ID
            $editData['id'] = $id ? $id : $result;
            die(JSON::encode(array('flag' => 'success', 'data' => $editData)));
        }
    }

    //批量删除规格
    function spec_del() {
        $id = IFilter::act(IReq::get('id'), 'int');
        if ($id) {
            $obj = M('spec');
            $data = array(
                'is_del' => 1
            );
            $obj->where(Util::joinStr($id))->save($data);
            $this->redirect('spec_list');
        } else {
            $this->redirect('spec_list', false);
            Util::showMessage('请选择要删除的规格');
        }
    }

    //彻底批量删除规格
    function spec_recycle_del() {
        $id = IFilter::act(IReq::get('id'), 'int');
        if ($id) {
            $obj = new IModel('spec');
            $obj->del(Util::joinStr($id));
            $this->redirect('spec_recycle_list');
        } else {
            $this->redirect('spec_recycle_list', false);
            Util::showMessage('请选择要删除的规格');
        }
    }

    //批量还原规格
    function spec_recycle_restore() {
        $id = IFilter::act(IReq::get('id'), 'int');
        if ($id) {
            $obj = new IModel('spec');
            $obj->setData(array('is_del' => 0));
            $obj->update(Util::joinStr($id));
            $this->redirect('spec_recycle_list');
        } else {
            $this->redirect('spec_recycle_list', false);
            Util::showMessage('请选择要还原的规格');
        }
    }
    
    //规格图片
    public function spec_photo(){
        $p = IFilter::act(IReq::get('p'), 'int') ? IFilter::act(IReq::get('p'), 'int') : 1;
        $order = 'id DESC';
        $page = '20';
        $spec_photoTB = M('spec_photo');
        $where = array();
        $spec_photo = $spec_photoTB->order($order)->where($where)->page($p . ",$page")->select();
        
        $count = $spec_photoTB->where($where)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //print_r($show);die;

        $this->assign('page', $show);
        $this->assign('spec_photo', $spec_photo);
        $this->display();
    }

    //规格图片删除
    function spec_photo_del() {
        $id = IReq::get('id', 'post');
        if (isset($id[0]) && $id[0] != '') {
            $obj = M('spec_photo');
            $id_str = '';
            foreach ($id as $rs) {
                if ($id_str != '') {
                    $id_str.=',';
                }
                $id_str.=$rs;

                $photoRow = $obj->field('address')->find($rs);
                if (file_exists($photoRow['address'])) {
                    unlink($photoRow['address']);
                }
            }

            $res = $obj->delete($id_str);
            $this->redirect('spec_photo');
        } else {
            $this->redirect('spec_photo', false, 0, '请选择要删除的id值');
        }
    }
    
    /*
     * 规格列表
     */
    function spec_list(){
        $spec_obj = M('spec');
        $where = array(
            'is_del' => '0',
        );
        $order = 'id desc';
        $spec = $spec_obj->where($where)->order($order)->page($_GET['p'] . ',20')->select();

        foreach ($spec as $key => $value) {
            $spec[$key]['spec'] = JSON::decode($value['value']);
        }
        //dump($spec);die;
        $count = $spec_obj->where($where)->count();
        $Page = new Page($count, 20);
        $show = $Page->show();
        //print_r($list);die;
        $this->assign('page', $show);
        $this->assign('spec',$spec);
        
        $this->display();
    }

    /**
     * @brief 分类排序
     */
    function category_sort() {
        $category_id = IFilter::act(IReq::get('id'), 'int');
        $sort = IFilter::act(IReq::get('sort'), 'int');

        $flag = 0;
        if ($category_id) {
            $tb_category = new IModel('category');
            $category_info = $tb_category->getObj('id=' . $category_id);
            if (count($category_info) > 0) {
                if ($category_info['sort'] != $sort) {
                    $tb_category->setData(array('sort' => $sort));
                    if ($tb_category->update('id=' . $category_id)) {
                        $flag = 1;
                    }
                }
            }
        }
        echo $flag;
    }
    
    /**
     * 品牌列表 
     */
    public function brand_list(){
        $p = $_GET['p'] ? $_GET['p'] : 1;
        $page = 20;
        $brand_obj = M('brand');
        $where = array(
            'is_del' => '0',
        );
        $order = 'sort asc';
        $brand = $brand_obj->where($where)->order($order)->page($p . ',' .$page)->select();
        $cat = M('brand_category')->select();
        foreach ($cat as $value) {
            $catAll[$value['id']] = $value['name'];
        }
        foreach ($brand as $key => $value) {
            $arr = explode(',', $value['category_ids']);
            foreach ($arr as $v) {
                $brand[$key]['category'] .=  $catAll[$v] . '&nbsp;';
            }
        }
        //dump($brand);die;
        $count = $brand_obj->where($where)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //print_r($list);die;
        $this->assign('page', $show);
        $this->assign('brand',$brand);
        $this->display();
    }

    /**
     * 品牌添加修改 
     */
    public function brand_edit() {
        $brand_id = (int) IReq::get('bid');
        //编辑品牌 读取品牌信息
        if ($brand_id) {
            $obj_brand = M('brand');
            $brand_info = $obj_brand->find($brand_id);
        }

        $obj_brand_category = M('brand_category');
        $brand_category = $obj_brand_category->select();
        $this->assign('brand' , $brand_info);
        $this->assign('brand_category' , $brand_category);
        $this->display();
    }
	/**
	 * @brief 保存品牌
	 */
	function brand_save()
	{
		$brand_id = IFilter::act(IReq::get('brand_id'));
		$name = IFilter::act(IReq::get('name'));
		$sort = IFilter::act(IReq::get('sort'));
		$url = IFilter::act(IReq::get('url'));
		$category = IFilter::act(IReq::get('category'));
		$description = IFilter::act(IReq::get('description'));

		$tb_brand = M('brand');
		$brand = array(
			'name'=>$name,
			'sort'=>$sort,
			'url'=>$url,
			'description' => $description,
		);

		if($category && is_array($category))
		{
			$categorys = join(',',$category);
			$brand['category_ids'] = $categorys;
		}
		else
		{
			$brand['category_ids'] = '';
		}
		if(isset($_FILES['logo']['name']) && $_FILES['logo']['name']!='')
		{
			$uploadObj = new PhotoUpload();
			$uploadObj->setIterance(false);
			$photoInfo = $uploadObj->run();
			if(isset($photoInfo['logo']['img']) && file_exists($photoInfo['logo']['img']))
			{
				$brand['logo'] = $photoInfo['logo']['img'];
			}
		}
		if($brand_id)
		{
			//保存修改分类信息
			$brand['id'] = $brand_id;
                        $tb_brand->save($brand);
		}
		else
		{
			//添加新品牌
			$tb_brand->add($brand);
		}
		$this->redirect('Goods/brand_list');
	}
    
    /*
     *  品牌分类列表
     */
    public function brand_category(){
        $p = IFilter::act(IReq::get('p'), 'int') ? IFilter::act(IReq::get('p'), 'int') : 1;
        $page = '20';
        $where = '';
        $order = '';
        
        $category_obj = M('brand_category');
        $category = $category_obj->where($where)->order($order)->page($p . ",$page")->select();
        $count = $category_obj->where($where)->count();
        $Page = new Page($count, $page);
        $show = $Page->show();
        //print_r($show);die;

        $this->assign('page', $show);
        $this->assign('category', $category);
        $this->display();
    }
    
    /*
     *  品牌分类修改
     */
    public function brand_category_edit(){
        
        $category_id = (int) IReq::get('id');
        //编辑品牌分类 读取品牌分类信息
        if ($category_id) {
            $obj_brand_category = M('brand_category');
            $category_info = $obj_brand_category->find($category_id);

            if ($category_info) {
                $this->catRow = $category_info;
            } else {
                $this->redirect('category_list');
                Util::showMessage("没有找到相关品牌分类！");
                return;
            }
        }
        $categoryObj = M('category');
        $categories = $categoryObj->select();
        $partnet = Goods::categoryParentStruct($categories);
        
        $this->assign('json_categories', JSON::encode($categories));
        $this->assign('json_partnet', JSON::encode($partnet));
        
        if($category_info['goods_category_id']){
            $default_cat = $categoryObj->where(array('id' => $category_info['goods_category_id']))->select();
            $this->assign('default_cat', JSON::encode($default_cat));
        }
        
        $this->assign('category_id', $category_id);
        $this->assign('json_category', JSON::encode($category_info));
        $this->display();
    }
    
    /**
     * 保存品牌分类 
     */
    public function brand_category_save() {
        $id = IFilter::act(IReq::get('id'));
        $goods_category_id = IFilter::act(IReq::get('goods_category_id'));
        $name = IFilter::act(IReq::get('name'));

        $category_info = array(
            'name' => $name,
            'goods_category_id' => $goods_category_id
        );
        $tb_brand_category = M('brand_category');

        //更新品牌分类
        if ($id) {
            $category_info['id'] = $id;
            $tb_brand_category->save($category_info);
        }
        //添加品牌分类
        else {
            $tb_brand_category->add($category_info);
        }
        $this->redirect('brand_category');
    }

    /**
     * @brief 品牌分类排序
     */
    public function brand_sort() {
        $brand_id = IFilter::act(IReq::get('id'), 'int');
        $sort = IFilter::act(IReq::get('sort'), 'int');
        $flag = 0;
        if ($brand_id) {
            $tb_brand = new IModel('brand');
            $brand_info = $tb_brand->getObj('id=' . $brand_id);
            if (count($brand_info) > 0) {
                if ($brand_info['sort'] != $sort) {
                    $tb_brand->setData(array('sort' => $sort));
                    if ($tb_brand->update('id=' . $brand_id)) {
                        $flag = 1;
                    }
                }
            }
        }
        echo $flag;
    }

    //修改排序
    public function ajax_sort() {
        $id = IFilter::act(IReq::get('id'), 'int');
        $sort = IFilter::act(IReq::get('sort'), 'int');

        $goodsDB = M('goods');
        $data = array(
            'sort' => $sort,
            'id' => $id
        );
        $goodsDB->save($data);
    }
    //商品预览
    public function home1(){
        $id = IFilter::act(IReq::get('id'), 'int');
        $info = M('goods')->where(array('id' => $id))->find();
        //将字符串进行处理
        $info['content']=stripslashes($info['content']);
        $info['content']=stripslashes($info['content']);
        //dump($info['content']);die;
        if($info['content']){
            $data = array(
                'status' => 1,
                'data' => $info['content']
            );
        }else{
            $data = array(
                'status' => 0
            );
        }
        echo json_encode($data);
    }
}
